'use strict';

const Controller = require('egg').Controller;

class MainController extends Controller {
    async index() {
        //
        let { role_id, is_super, username } = this.ctx.session.userinfo
        //
        let result = await this.ctx.model.Access.findAll({
            where: {
                moduleId: 0
            },
            include: { model: this.ctx.model.Access }
        });

        //
        let resultRole = await this.app.mysql.query('select access_id from role_access where role_id =?', [role_id])


        var temp = []
        for (let i = 0; i < resultRole.length; i++) {
            temp.push(resultRole[i].access_id);
        }

        result = JSON.parse(JSON.stringify(result))
        for (let i = 0; i < result.length; i++) {
            if (temp.indexOf(result[i].id) != -1) {
                result[i].checked = true
            }
            for (let j = 0; j < result[i].accesses.length; j++) {
                if (temp.indexOf(result[i].accesses[j].id) != -1) {
                    result[i].accesses[j].checked = true
                }
            }
        }
        await this.ctx.render(`admin/main/index`, {
            list: result,
            is_super,
            username
        })
    }

    async welcome() {
        await this.ctx.render(`admin/main/welcome`)
    }

    async touch() {
        let { id, query, state } = this.ctx.query

        if (state != 1) {
            state = 1
        } else {
            state = 0
        }

        var sql = `update product set ${query}=? where id=?`
        let result = await this.app.mysql.query(sql, [state, id])

        if (result.protocol41) {
            this.ctx.body = {success:1,msg:"修改成功"}
        } else {
            this.ctx.body = {success:0,msg:"修改失败"}
        }
      
    }
}

module.exports = MainController;
